var MongoClient = require('mongodb').MongoClient;
var async = require('async');
var driver = require('./db');
var utils = require('./utils');


const Url = "mongodb://localhost:27017/manhua";

const table = 'historys';


var historysDao = {};

// 添加
historysDao.add = function (param, userId, res) {

    var _query = {
        "userId": require('mongodb').ObjectID(userId),
        "manhuaId": require('mongodb').ObjectID(param['_id'])
    };



    var data = {
        "title": param.title,
        "img": param.img,
        "userId": require('mongodb').ObjectID(userId),
        "manhuaId": require('mongodb').ObjectID(param['_id']),
        "readChapter": param.readChapter,
        "readChapterHref": param.readChapterHref,
        "chapterLength":param.chapterLength,
        "isNew": false,
        "readTime": new Date()
    };

    async.waterfall([
        // 连接数据库        
        function (callback) {
            driver.connect(callback, Url);
        },
        // 超找
        function (db, callback) {

            driver.find(db, callback, table, _query);
        },
        // 插入
        function (db, res, callback) {

            if (res.data.length == 0) {

                driver.insert(db, callback, table, data);

            } else {
                driver.update(db, callback, table, _query, data);
            }


        },
        function (db, res, callback) {
            driver.close(db, res, callback);
        }],
        // result
        function (err, result) {
            console.log("resulte");

            if (err) {
                res.json(err);
                return;
            }
            res.json(result);
        }
    );
};

// 删除
historysDao.del = function (param, userId, res) {

    var _query = {
        "_id": require('mongodb').ObjectID(param['_id'])
    };

    async.waterfall([
        // 连接数据库        
        function (callback) {
            driver.connect(callback, Url);
        },
        // 查询
        function (db, callback) {

            driver.find(db, callback, table, _query);
        },
        // 删除
        function (db, res, callback) {

            if (res.data.length > 0) {
                driver.delete(db, callback, table, _query);
            } else {
                callback({ success: false, msg: '该漫画历史已经删除' }, db, res);
            }


        },
        function (db, res, callback) {
            driver.close(db, res, callback);
        }],
        // result
        function (err, result) {
            console.log("resulte");

            if (err) {
                res.json(err);
                return;
            }
            res.json(result);
        }
    );
};

// 查询
historysDao.search = function (param, userId, res) {

    var _query = {
        "userId": require('mongodb').ObjectID(userId)
    };

    // 时间筛选
    if (param.date) {
        var nowDate = new Date(), nowDateString;
        switch (param.date) {
            case "today":
                nowDateString = utils.dateFormat(nowDate);

                _query['readTime'] = {
                    "$lt": new Date(nowDateString + " 23:59:59"),
                    "$gt": new Date(nowDateString + " 00:00:00")
                };

                break;
            case "yestoday":
                nowDate.setDate(nowDate.getDate() - 1);
                nowDate = new Date(nowDate);
                nowDateString = utils.dateFormat(nowDate);
                _query['readTime'] = {
                    "$lt": new Date(nowDateString + " 23:59:59"),
                    "$gt": new Date(nowDateString + " 00:00:00")
                };
                nowDateString = null;
                break;
            case "yestodayBefore":
                nowDate.setDate(nowDate.getDate() - 2);
                nowDate = new Date(nowDate);
                nowDateString = utils.dateFormat(nowDate);
                _query['readTime'] = {
                    "$lt": new Date(nowDateString + " 23:59:59"),
                    "$gt": new Date(nowDateString + " 00:00:00")
                };
                nowDateString = null;
                break;
            case "more":
                nowDate.setDate(nowDate.getDate() - 3);
                nowDate = new Date(nowDate);
                nowDateString = utils.dateFormat(nowDate);
                _query['readTime']= {
                    "$lt": new Date(nowDateString + " 23:59:59")
                };
                nowDateString = null;
                break;
            default:
                res.json({
                    success: false,
                    msg: '缺少时间参数'
                });
                return;
                break;
        }
        nowDateString = null; nowDate = null;
    }


    async.waterfall([
        // 连接数据库        
        function (callback) {
            driver.connect(callback, Url);
        },
        // 查询
        function (db, callback) {

            driver.find(db, callback, table, _query);
        },
        function (db, res, callback) {
            driver.close(db, res, callback);
        }],
        // result
        function (err, result) {
            console.log("resulte");

            if (err) {
                res.json(err);
                return;
            }
            res.json(result);
        }
    );
};

// 修改
historysDao.update = function (param, userId, res) {

    var _query = {
        "userId": require('mongodb').ObjectID(userId),
        "manhuaId": require('mongodb').ObjectID(param['_id'])
    };

    var data = {
        "readChapter": param.readChapter,
        "readChapterHref": param.readChapterHref,
        "isNew": param['isNew'] || false,
        "readTime": new Date()
    };

    async.waterfall([
        // 连接数据库        
        function (callback) {
            driver.connect(callback, Url);
        },
        // 超找
        function (db, callback) {

            driver.find(db, callback, table, _query);
        },
        // 插入
        function (db, res, callback) {

            if (res.data.length == 0) {
                callback({ success: false, msg: '该漫画历史已经删除' }, db, res);
            } else {
                driver.update(db, callback, table, _query, data);
            }


        },
        function (db, res, callback) {
            driver.close(db, res, callback);
        }],
        // result
        function (err, result) {
            console.log("resulte");

            if (err) {
                res.json(err);
                return;
            }
            res.json(result);
        }
    );
};

// f分页
historysDao.page = function(param,userId,res){
    var _query = {
        "userId": require('mongodb').ObjectID(userId)
    };

    // 时间筛选
    if (param.date) {
        var nowDate = new Date(), nowDateString;
        switch (param.date) {

            case "today":
                nowDateString = utils.dateFormat(nowDate);

                _query['readTime'] = {
                    "$lt": new Date(nowDateString + " 23:59:59"),
                    "$gt": new Date(nowDateString + " 00:00:00")
                };

                break;
            case "yestoday":
                nowDate.setDate(nowDate.getDate() - 1);
                nowDate = new Date(nowDate);
                nowDateString = utils.dateFormat(nowDate);
                _query['readTime'] = {
                    "$lt": new Date(nowDateString + " 23:59:59"),
                    "$gt": new Date(nowDateString + " 00:00:00")
                };
                nowDateString = null;
                break;
            case "yestodayBefore":
                nowDate.setDate(nowDate.getDate() - 2);
                nowDate = new Date(nowDate);
                nowDateString = utils.dateFormat(nowDate);
                _query['readTime'] = {
                    "$lt": new Date(nowDateString + " 23:59:59"),
                    "$gt": new Date(nowDateString + " 00:00:00")
                };
                nowDateString = null;
                break;
            case "more":
                nowDate.setDate(nowDate.getDate() - 3);
                nowDate = new Date(nowDate);
                nowDateString = utils.dateFormat(nowDate);
                _query['readTime']= {
                    "$lt": new Date(nowDateString + " 23:59:59")
                };
                nowDateString = null;
                break;
            default:
                break;
        }
        nowDateString = null; nowDate = null;
    }

    var page_size = Number(param.size) || 10;

    var page_cur = Number(param.curPage) || 1;

    async.waterfall([
        // 连接数据库        
        function (callback) {
            driver.connect(callback, Url);
        },
        // 查询
        function (db, callback) {
            driver.page(db, callback, table, _query, {}, page_cur, page_size, {readTime: -1});
            // driver.find(db, callback, table, _query);
        },
        function (db, res, callback) {
            driver.close(db, res, callback);
        }],
        // result
        function (err, result) {
            console.log("resulte");

            if (err) {
                res.json(err);
                return;
            }
            res.json(result);
        }
    );
};
module.exports = historysDao;